package cn.bbstone.pisces2.client.task.impl;

import cn.bbstone.pisces2.client.base.ClientCache;
import cn.bbstone.pisces2.client.task.TaskListener;
import cn.bbstone.pisces2.client.task.event.FailEvent;
import cn.bbstone.pisces2.client.task.event.FailEventData;
import cn.bbstone.pisces2.comm.fli.FliSavePoint;
import cn.bbstone.pisces2.util.FLIUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class FileTaskListener implements TaskListener {
    private static Logger log = LoggerFactory.getLogger(FileTaskListener.class);

    @Override
    public void onCompleted(FliSavePoint fliSavePoint) {
        // update fli.sp (fileNo and updateTime) when one file recv completed
        FliSavePoint fliSavePointDisk = FLIUtil.readClientSavePoint();
        fliSavePointDisk.setFileNo(fliSavePoint.getFileNo());
        fliSavePointDisk.setUpdateTime(System.currentTimeMillis());
        FLIUtil.writeClientSavePoint(fliSavePointDisk);
        // calculate cost time
        FileTask fileTask = ClientCache.getTask(fliSavePoint.getFileNo());
        long oneFileTransferCostTimeMs = fileTask.costTimeMs();
        log.debug("<><>====<><> transfer file(fielNo: {}) cost time: {} ms. clientCache.size: {}",
                fliSavePoint.getFileNo(), oneFileTransferCostTimeMs, ClientCache.size());
        ClientCache.accumulateCostTime(oneFileTransferCostTimeMs);
//        fileTask.closeFos();
        //remove file task of fileNo
        ClientCache.removeTask(fliSavePoint.getFileNo());

    }

    @Override
    public void onFail(FailEvent failEvent) {
        FailEventData failEventData = failEvent.getFailEventData();
        //remove file task of fileNo
        ClientCache.removeTask(failEventData.getFileNo());
        log.error("fileNo({}) received file data error, reason: {}",
                failEventData.getFileNo(), failEventData.getReason());
    }
}
